package com.uhylab.uhuvinetest.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.uhylab.uhuvinetest.R;
import com.uhylab.uhuvinetest.base.UHBase;
import com.uhylab.uhuvinetest.base.UHBaseActivity;
import com.uhylab.uhuvinetest.bean.StringData;
import com.uhylab.uhuvinetest.utils.StringUtils;
import com.uhylab.uhuvinetest.utils.VolleySingleton;
import com.zhy.autolayout.AutoRelativeLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;


/**
 * Created by xyb on 16/1/7 at UHylab
 *
 * @version 1.0
 */
public class UHRegisteredActivity extends UHBaseActivity implements View.OnClickListener, Handler.Callback, CompoundButton.OnCheckedChangeListener {
    private Handler handler;
    private TextView send_sms_Button;
    private AutoRelativeLayout regestButton;
    //    private Toolbar toolbar;
    private EditText user_telphone;
    public String phString = ""; // 手机号
    String user_password_string = "65456465"; // 密码
    // 填写从短信SDK应用后台注册得到的APPKEY
    private static String APPKEY = "dd6203e0d9e2";

    // 填写从短信SDK应用后台注册得到的APPSECRET
    private static String APPSECRET = "80bfc666a79309b55a0ef7676ec63125";
    Thread thread = null;
    private int i = 60;
    private boolean tag = true;
    private EditText user_password, user_regset;
    private boolean isget = false;// 是否获取验证码
    private CheckBox checkBox;
    private VolleySingleton volleySingleton;
    private EventHandler eh;
    private TextView protocol;
    private ImageView register_back;
    private TextView register_logon;

    @Override
    public int bindLayout() {
        return R.layout.activity_registeredtwo;
    }

    @Override
    public void initView(View view) {
        volleySingleton = VolleySingleton.getVolleySingleton(getApplicationContext());
        initRegisterView(view);
        initHandler();
    }

    private void initRegisterView(View view) {
        send_sms_Button = (TextView) view.findViewById(R.id.send_sms_Button);
        user_telphone = (EditText) view.findViewById(R.id.user_telphone);
        regestButton = (AutoRelativeLayout) view.findViewById(R.id.register_Button);
        user_password = (EditText) view.findViewById(R.id.user_password);
        user_regset = (EditText) view.findViewById(R.id.user_regset);
        checkBox = (CheckBox) view.findViewById(R.id.password_checkBox);
        protocol = (TextView) view.findViewById(R.id.user_protocol);
        register_back = (ImageView) view.findViewById(R.id.register_back);
        register_logon = (TextView) view.findViewById(R.id.register_logon);
    }

    private void initHandler() {
        handler = new Handler(this);
    }

    private void initSDK() {
        // 初始化短信SDK
        SMSSDK.initSDK(this, APPKEY, APPSECRET);
        eh = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }
        };
        SMSSDK.registerEventHandler(eh);
    }

    @Override
    public void doBusiness(Context mContext) {
        send_sms_Button.setOnClickListener(this);
        regestButton.setOnClickListener(this);
        checkBox.setOnCheckedChangeListener(this);
        register_logon.setOnClickListener(this);
        register_back.setOnClickListener(this);
        protocol.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UHRegisteredActivity.this, UHWebViewActivity.class);
                intent.putExtra("title", "服务协议");
                intent.putExtra("url", "file:///android_asset/protocol.html");
                UHRegisteredActivity.this.startActivity(intent);
            }
        });
    }

    @Override
    public void resume() {
        initSDK();
    }

    private void isregest() {
        volleySingleton.removeRequest("isregest");
        StringRequest stringRequest = new StringRequest(Request.Method.GET, UHBase.newRegisteredUrl + "?phone=" + phString, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    Log.e("UHHomeFragment", response);
                    Gson gson = new Gson();
                    StringData dataee = gson.fromJson(response, StringData.class);
                    if (dataee.getCode().equals("0102")) {
                        Log.e("UHRegisteredActivity", phString);
                        Toast.makeText(UHRegisteredActivity.this, dataee.getMsg(), Toast.LENGTH_SHORT).show();
                    } else {
                        SMSSDK.getVerificationCode("86", phString);
                    }
                } catch (Exception e) {
                    Toast.makeText(UHRegisteredActivity.this, "获取失败请重试", Toast.LENGTH_SHORT).show();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("UHHomeFragment", "error:" + error);
            }
        }) {
//            @Override
//            protected Map<String, String> getParams() throws AuthFailureError {
//                //在这里设置需要post的参数
//                Map<String, String> params = new HashMap<String, String>();
//                Log.e("UHRegisteredIs", phString);
//                params.put("telephone", phString);
//                return params;
//            }
        };
        volleySingleton.addQueue(stringRequest, "isregest");
    }


    private void regest() {

        //在这里设置需要post的json格式的数据
        Map<String, String> params = new HashMap<String, String>();
        params.put("phone", phString);
        params.put("password", user_password_string);
        params.put("vercode", user_telphone.getText().toString());
        params.put("isthird", user_telphone.getText().toString());
        JSONObject jsonObject = new JSONObject(params);


        JsonObjectRequest regest = new JsonObjectRequest(Request.Method.POST, UHBase.newRegisteredUrl, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.e("UHHomeFragment", response.toString());
                try {
                    Gson gson = new Gson();
                    StringData dataee = gson.fromJson(response.toString(), StringData.class);
                    if (dataee.getCode().equals("0000")) {
                        Toast.makeText(UHRegisteredActivity.this, dataee.getMsg(), Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(UHRegisteredActivity.this, UHLogonActivity.class);
                        intent.putExtra("telephone", phString);
                        intent.putExtra("password", user_password_string);
                        startActivity(intent);
                        finish();
                    } else {

                    }
                } catch (Exception e) {
                    Log.e("UHRegisteredActivity", "接口出错");
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("UHHomeFragment", "retrievePass + error:" + error);
            }
        }) {
            //            @Override
//            protected Map<String, String> getParams() throws AuthFailureError {
//                //在这里设置需要post的参数
//                Map<String, String> params = new HashMap<String, String>();
//                params.put("telephone", phString);
//                params.put("password", user_password_string);
//                return params;
//            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Accept", "application/json");
                headers.put("Content-Type", "application/json; charset=UTF-8");

                return headers;
            }


        };
        volleySingleton.addQueue(regest, "Request");
    }


    @Override
    public void destroy() {
        SMSSDK.unregisterEventHandler(eh);
        volleySingleton.removeRequest("Request");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send_sms_Button:
                phString = user_telphone.getText().toString();
                if (!TextUtils.isEmpty(phString)) {
                    if (StringUtils.isPhoneNumberValid(phString)) {

                        isregest();
                    } else {
                        Toast.makeText(this, "手机号输入错误", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(this, "电话不能为空", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.register_Button:
                if (isget) {
                    user_password_string = user_password.getText().toString();
                    if (!TextUtils.isEmpty(user_password_string)) {
                        if (user_password_string.length() >= 6) {
                            if (!TextUtils.isEmpty(user_regset.getText().toString())) {
                                SMSSDK.submitVerificationCode("86", phString, user_regset.getText().toString());
                            } else {
                                Toast.makeText(this, "验证码不能为空", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(this, "请输入6位以上密码", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(this, "请获取验证码", Toast.LENGTH_SHORT).show();
                }
                break;

            case R.id.register_back:
                finish();

                break;
            case R.id.register_logon:
                Intent intent = new Intent(this, UHLogonActivity.class);
                startActivity(intent);
                finish();
                break;
        }
    }

    // 获取验证码等待
    private void changeBtnGetCode() {
        thread = new Thread() {
            @Override
            public void run() {
                if (tag) {
                    while (i > 0) {
                        i--;
                        if (UHRegisteredActivity.this == null) {
                            break;
                        }

                        UHRegisteredActivity.this
                                .runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        send_sms_Button.setText("获取验证码("
                                                + i + ")");
                                        send_sms_Button.setClickable(false);
                                    }
                                });
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    tag = false;
                }
                i = 60;
                tag = true;
                if (UHRegisteredActivity.this != null) {
                    UHRegisteredActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            send_sms_Button.setText("获取验证码");
                            send_sms_Button.setClickable(true);
                        }
                    });
                }
            }
        };
        thread.start();
    }

    @Override
    public boolean handleMessage(Message msg) {

        int event = msg.arg1;
        int result = msg.arg2;
        Object data = msg.obj;
        Log.e("event", "event=" + event + "result" + result);
        if (result == SMSSDK.RESULT_COMPLETE) {
            //短信注册成功后，返回MainActivity,然后提示新好友
            if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                //提交验证码成功
//                Toast.makeText(getApplicationContext(), "提交验证码成功", Toast.LENGTH_SHORT).show();
                volleySingleton.removeRequest("isregest");
                regest();
            } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
//                Toast.makeText(UHRegisteredActivity.this, "验证码已经发送", Toast.LENGTH_SHORT).show();
                user_regset.setText("");
                changeBtnGetCode();
                isget = true;
            } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {//返回支持发送验证码的国家列表
                Toast.makeText(UHRegisteredActivity.this, "获取国家列表成功", Toast.LENGTH_SHORT).show();

            }
        } else {
            Throwable throwable = (Throwable) data;
            throwable.printStackTrace();
            JSONObject object;
            try {
                object = new JSONObject(throwable.getMessage());
                int status = object.optInt("status");//错误代码
                Log.e("UHRegisteredActivity", "status:" + status);
                if (status > 0) {
                    if (status == 478) {
                        Toast.makeText(this, "获取超限明日再来", Toast.LENGTH_SHORT).show();
                    } else if (status == 468) {
                        Toast.makeText(this, "验证码输入错误", Toast.LENGTH_SHORT).show();
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            user_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            user_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }

    }
}
